const fs = require('fs')
const path = require('path')
const makeDir = require('make-dir')
const del = require('del')
const { adduserImportList } = require('../utils/ImportUtil')
const { getPluginOptions } = require('../utils/PluginOptionsUtil')

module.exports = (userOptions, nodeApp) => {
  // vue模板文件缓存路径
  let vueDirTemp = path.resolve(__dirname, '../vue/temp')
  try {
    // @ts-ignore
    fs.accessSync(vueDirTemp, fs.F_OK)
    del.sync(vueDirTemp)
    // console.log('删除', vueDirTemp)
  } catch (e) {
    // console.log('--->', e)
  }

  makeDir.sync(vueDirTemp)
  // 初始化importCompList.js
  fs.writeFileSync(path.resolve(vueDirTemp, 'importCompList.js'), `export function getCompList(){return []}`)

  // md中导出来的组件列表
  let importCodeList = {
    // import xxx from xxxx
    importList: [],
    // vue路径文件
    compPathList: [],
    // '{ name: '${compName}', item: ${compName} }'
    compInfoList: []
  }

  // { compItemList: [ { isInstall: true, pathList: [Array] } ] }
  if (userOptions) {
    let compItemList = userOptions['compItemList'] || []
    let stylePathList = userOptions['stylePathList'] || []
    adduserImportList(importCodeList, compItemList, stylePathList)
  }

  // ::: demo
  let demoBlockName = (userOptions && userOptions['demoBlockName']) || 'demo'

  // vuepress版本
  let version = (userOptions && userOptions['vuepressVersion']) || 2

  //
  let options = {
    // 缓存路径
    vueDirTemp: vueDirTemp,
    // container容器的名称
    demoBlockName: demoBlockName,
    // 导入组件或样式列表
    importCodeList: importCodeList
  }
  let opts = getPluginOptions(version, options)
  return opts
}
